//
//  GJMapViewController.m
//  xmgjAppFront
//
//  Created by Zeki on 2020/7/10.
//  Copyright © 2020 guojutech. All rights reserved.
//

#import "GJMapViewController.h"
#import "GJFillUPMapBottomView.h"
#import "GJPetrolStationModel.h"
#import "GJAnnotation.h"
#import "GJCommonAnnotationView.h"
#import "GJMapService.h"
#import "GJOilSelectedView.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
@interface GJMapViewController ()<MAMapViewDelegate>
//当前界面的mapView
@property (nonatomic, strong) MAMapView *mapView;
//当前位置对象
@property (nonatomic, strong) MAUserLocation *userLocation;//用户定位的位置
@property (nonatomic, strong) MAPointAnnotation *userAnnotation;//用户定位标记

@property (nonatomic, strong) GJLocationUtil *util;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) GJCommonAnnotationView *selectedAnnotationView;//选中的标记点
@property (nonatomic, strong) GJFillUPMapBottomView *bottomView;//底部视图

@property (nonatomic, strong) UIButton *locationBtn;//定位按钮
@property (nonatomic, strong) UIButton *menuBtn;//菜单按钮
@property (nonatomic, strong) UIButton *navBackBtn;//导航栏返回按钮
@property (nonatomic, strong) GJOilSelectedView *selectedView;//选择油品

@property (nonatomic, strong) GJOilClassificationModel *currentOilTypeModel;//当前model


@end

@implementation GJMapViewController


- (void)viewDidLoad {
  [super viewDidLoad];
  [self initlizationSubViews];
  [self updateLocation];
  [self queryOilClassification];
  if ([self.businessNo gj_hasValue]) {
    self.selectedView.oilType = self.businessNo;
  }else{
    self.selectedView.oilType = @"0";
  }
}


- (void)initlizationSubViews{
  //将mapView添加到当前视图中
  [self.view addSubview:self.mapView];
  [self.mapView addSubview:self.bottomView];
  [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.mas_equalTo(-kSafeBottomAreaHeight - 6);
    make.left.mas_equalTo(16);
    make.right.mas_equalTo(-16);
    make.height.mas_equalTo(self.bottomView.viewHeight);
  }];
  
  [self.mapView addSubview:self.locationBtn];
  [self.mapView addSubview:self.menuBtn];
  
  [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.bottomView.mas_top).offset(-20);
    make.width.height.mas_equalTo(38);
    make.right.equalTo(self.mapView).offset(-16);
  }];
  [self.menuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.locationBtn.mas_top).offset(-12);
    make.width.height.mas_equalTo(38);
    make.right.equalTo(self.mapView).offset(-16);
  }];
  
  
  [self.mapView addSubview:self.selectedView];
  [self.selectedView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.height.equalTo(self.locationBtn);
    make.left.mas_equalTo(16);
    make.width.mas_equalTo(71);
  }];
  
  [self.mapView addSubview:self.navBackBtn];
  [self.navBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.mas_equalTo(kSafeNavigationBarHeight - 20);
    make.width.height.mas_equalTo(32);
    make.left.mas_equalTo(16);
  }];
}

#pragma mark -- btnAction
- (void)buttonClickAction:(UIButton *)sender{
  switch (sender.tag) {
    case 100: case 99:
    {
      //menuBtn
      [self dismissViewControllerAnimated:YES completion:nil];
    }
      break;
    case 101:
    {
      //locationBtn
      [self updateLocation];
    }
      break;
    default:
      break;
  }
}

#pragma mark -- location
/// 更新定位位置
- (void)updateLocation{
  MBProgressHUD *hud = [MBProgressHUD cr_showLoadinWithView:self.view text:@""];
  @weakify(self);
  __block NSInteger cycleTime = 5;
  [[GJLocationUtil shareInstance] getLocationWithCommplete:^(CLLocationCoordinate2D coordinate, NSDictionary * _Nonnull addressDic, NSError * _Nonnull error) {
    @strongify(self);
    if (error!=nil) {
      cycleTime --;
      if (cycleTime<=0) {
        [hud cr_hide];
        [MBProgressHUD cr_showToastWithView:self.view text:@"获取位置信息失败"];
        [[GJLocationUtil shareInstance] stopSerialLocation];
      }
      return;
    }
    [hud cr_hide];
    //停止更新位置信息
    [[GJLocationUtil shareInstance] stopSerialLocation];
    //记录我的位置信息
    if (!self.userLocation) {
      self.userLocation = [[MAUserLocation alloc] init];
    }
    self.userLocation.coordinate = coordinate;
    //展示我的位置图标
    [self.mapView setCenterCoordinate:coordinate animated:YES];
    self.userAnnotation.coordinate = coordinate;
    [self.mapView removeAnnotation:self.userAnnotation];
    [self.mapView addAnnotation:self.userAnnotation];
    //查询加油站列表
    [self queryPetrolStations:self.userAnnotation.coordinate];
  }];
}

///查询附近加油站
- (void)queryPetrolStations:(CLLocationCoordinate2D)coordinate{
  MBProgressHUD *hud = [MBProgressHUD cr_showLoadinWithView:self.view text:@""];
  //查询附近加油站列表
  @weakify(self);
  //  102.562576,24.384602
  [[GJMapService shareInstance] queryArroundPetrolStationListWith:coordinate distance:@"9999" businessNo:[self.businessNo gj_hasValue] ? self.businessNo : @"0" commplete:^(GJResult * _Nonnull result) {
    [hud cr_hide];
    @strongify(self);
    NSArray *data = result.successData;
    if (data.count > 0 ) {
      [data each:^(GJAnnotation * object) {
        if (object.isNearest) {
          self.bottomView.model = object.model;
        }
      }];
      
      self.dataSource = [data mutableCopy];
      [self.mapView addAnnotations:self.dataSource];
//      [[GJLocationUtil shareInstance] zoomMapViewToFitAnnotations:self.mapView animated:YES];
      //自动显示所有annotation
//      [self.mapView showAnnotations:self.dataSource animated:YES];
    }
  }];
}
- (void)queryOilClassification{
  MBProgressHUD *hud = [MBProgressHUD cr_showLoadinWithView:self.view text:@""];
  [[GJMapService shareInstance] queryOilClassification:^(GJResult * _Nonnull result) {
    [hud cr_hide];
    if (result.isSuccess) {
      NSArray *dataArray  = result.successData;
      [dataArray map:^id(GJOilClassificationModel* object) {
        if ([object.businessNo isEqualToString:self.businessNo]) {
          object.isSelected = YES;
        }else{
          object.isSelected = NO;
        }
        return object;
      }];
      self.selectedView.dataArray = dataArray;
    }
  }];
}

#pragma mark -- BMKMapViewDelegate
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate{
  self.userLocation.coordinate = coordinate ;
  //切换地图中心位置
  [mapView setCenterCoordinate:coordinate animated:YES];
  self.userAnnotation.coordinate = coordinate;
  [mapView removeAnnotation:self.userAnnotation];
  [mapView addAnnotation:self.userAnnotation];
  [self queryPetrolStations:self.userAnnotation.coordinate];
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
  
  
  if ([annotation isKindOfClass:[GJAnnotation class]]) {
    GJCommonAnnotationView *annotationView = (GJCommonAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"otherAnnotationView"];
     if (annotationView == nil) {
       annotationView = [[GJCommonAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"otherAnnotationView"];
     }
     
     GJAnnotation *myAnnotation = (GJAnnotation *)annotation;
     if (myAnnotation.isNearest) {
       annotationView.image = [UIImage imageNamed:@"mapModule_PetrolStationSelected"];
       self.selectedAnnotationView = annotationView;
       self.bottomView.model = myAnnotation.model;
     }else{
       annotationView.image = [UIImage imageNamed:@"mapModule_PetrolStationNominal"];
     }
     
     
     annotationView.canShowCallout = NO;
     return annotationView;
  }else{
    static NSString *reuseIndetifier = @"annotationReuseIndetifier";
    MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    if (annotationView == nil)
    {
      annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                     reuseIdentifier:reuseIndetifier];
    }
    
    annotationView.image = [UIImage imageNamed:@"mapModule_position_selected.png"];
    return annotationView;
  }
 return nil;
}



- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
  if ([view isKindOfClass:[GJCommonAnnotationView class]]) {
    GJCommonAnnotationView *selectedAnnotationView = (GJCommonAnnotationView *)view;
    if ((selectedAnnotationView.annotation.coordinate.latitude != self.selectedAnnotationView.annotation.coordinate.latitude) && (selectedAnnotationView.annotation.coordinate.longitude != self.selectedAnnotationView.annotation.coordinate.longitude)) {
      view.image = [UIImage imageNamed:@"mapModule_PetrolStationSelected"];
      self.selectedAnnotationView.image = [UIImage imageNamed:@"mapModule_PetrolStationNominal"];
      self.selectedAnnotationView = selectedAnnotationView;
      //更改地图的中心
      [self.mapView setCenterCoordinate: self.selectedAnnotationView.annotation.coordinate animated:YES];
      //更新bottomview
      GJAnnotation *myAnnotation =(id)view.annotation;
      self.bottomView.model = myAnnotation.model;
    }
  }
}

#pragma mark -- getter
- (MAMapView *)mapView{
  if (!_mapView) {
    _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    //设置mapView的代理
    _mapView.delegate = self;
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = MAUserTrackingModeNone;
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    _mapView.zoomLevel = 15;
    for (UIView *view in _mapView.subviews) {
      if ([view isKindOfClass:[UIImageView class]]) {
        [view removeFromSuperview];
      }
    }
  }
  return _mapView;
}
- (GJLocationUtil *)util{
  if (!_util) {
    _util = [GJLocationUtil new];
  }
  return _util;;
}

- (NSMutableArray *)dataSource{
  if (!_dataSource) {
    _dataSource = [NSMutableArray new];
  }
  return _dataSource;
}

- (GJFillUPMapBottomView *)bottomView{
  if (!_bottomView) {
    _bottomView = [GJFillUPMapBottomView new];
  }
  return _bottomView;;
}

- (UIButton *)locationBtn{
  if (!_locationBtn) {
    _locationBtn = [UIButton new];
    [_locationBtn setImage:[UIImage imageNamed:@"mapModule_location"] forState:UIControlStateNormal];
    _locationBtn.tag = 101;
    [_locationBtn addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _locationBtn;
}
- (UIButton *)menuBtn{
  if (!_menuBtn) {
    _menuBtn = [UIButton new];
    [_menuBtn setImage:[UIImage imageNamed:@"mapModule_menu"] forState:UIControlStateNormal];
    _menuBtn.tag = 100;
    [_menuBtn addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _menuBtn;
}

- (UIButton *)navBackBtn{
  if (!_navBackBtn) {
    _navBackBtn = [UIButton new];
    [_navBackBtn setImage:[UIImage imageNamed:@"mapModule_back"] forState:UIControlStateNormal];
    _navBackBtn.backgroundColor = HexColor(#343332);
    _navBackBtn.layer.cornerRadius = 16;
    _navBackBtn.layer.masksToBounds = YES;
    _navBackBtn.tag = 99;
    [_navBackBtn addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _navBackBtn;
}
- (GJOilSelectedView *)selectedView{
  if (!_selectedView) {
    _selectedView = [GJOilSelectedView new];
    @weakify(self);
    _selectedView.itemClickBlcok = ^(GJOilClassificationModel * _Nonnull model) {
      //拉取新油站数据
      @strongify(self);
      //清空地图标志
      [self.mapView removeAnnotations:self.dataSource];
      [self.bottomView showNoneDataView:YES];
      self.businessNo = model.businessNo;
//      [self updateLocation];
      [self queryPetrolStations:self.userLocation.location.coordinate];
      [self.selectedView.dataArray map:^id(GJOilClassificationModel* object) {
        if ([object.businessNo isEqualToString:self.businessNo]) {
          object.isSelected = YES;
          self.selectedView.selectedModel = object;
        }else{
          object.isSelected = NO;
        }
        return object;
      }];
    };
  }
  return _selectedView;
}
- (MAPointAnnotation *)userAnnotation{
  if (!_userAnnotation) {
    _userAnnotation = [MAPointAnnotation new];
  }
  return _userAnnotation;
}
@end
